import fse from 'fs-extra';
import path from 'path';

import { addOhPackageDps, buildOneHapAndCheckFile, commonFileOperation, resourcesPath } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },

  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1,
  }
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 复制ohpm包到application目录下
  const applicationPath = project.getModule('application').moduleRootPath();
  await fse.copy(path.resolve(resourcesPath, 'extra/staticlibrary'), path.resolve(applicationPath, 'staticlibrary'));

  // 2. 使application模块依赖har模块
  await addOhPackageDps(applicationPath, {
    '@ohos/staticlibrary': './staticlibrary'
  });

  // 3. 在index文件中依赖har中的字符串资源
  await commonFileOperation(path.resolve(applicationPath, 'src/main/ets/pages/Index.ets'), async (buffer) => {
    const content = buffer.toString();
    return content.replace('this.message', '$r(\'app.string.page_show\')');
  });

  // 4. 构建hap
  await buildOneHapAndCheckFile('application')(project, taskConfig, record);
};

// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_Feature_Shared_Modules_HOS_api10_STAGE_003')
  .description('3.新模型工程feature-stage-eTS引用本地ets+npm包资源')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testFun)
  .load();
